package Connections;

import Gear.Factory;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;


/**
 * Client to download files from a peer server.
 *
 * @author Rodrigo Martins Racanicci
 */
public class DownloaderClient extends Client {

    /**
     * Constructor.
     *
     * @param serverHost Peer server host.
     */
    public DownloaderClient(String serverHost) {
        super(serverHost.substring(1));
    }

    /**
     * Download a file from a peer server.
     *
     * @param fileName File name to download.
     */
    public void dowload(String fileName) {
        sendCommand("ResquestFile \"" + fileName + "\"");
        if (receiveCommand().equals("Ok")) {
            try {
                Files.deleteIfExists(FileSystems.getDefault().getPath(Factory.getInstance().getSettings().getGearPath().toString(), fileName));
            } catch (IOException ex) {
            }
            receiveFile(fileName);
        } else {
            System.out.println("The file " + fileName + " isnt available anymore!");
            close();
        }

    }

    /**
     * Syncronize a file with the peer.
     *
     * @param fileName File name to syncronize.
     * @param peer     Peer host.
     */
    public void syncFile(String fileName, String peer) {
        sendCommand("SyncFile \"" + fileName + "\"\"" + peer + "\"");
        close();
    }

}
